import { JXDef, JXMath } from "../../../conventions/JXCommon";
import { PRIORITY_VIEW } from "../../../Core/CoreDefine";
import GParam from "../../../Core/GEvent/GParam";
import { GListView } from "../../../Core/GView/GListView";
import GViewBase from "../../../Core/GView/GViewBase";
import { AudioMgr } from "../../../Core/Manager/AudioMgr";
import { ComonTip, CURRENCY, HERO_TRAIT, ITEM_DETAIL_FLAG, ITEM_TYPE, RANGE, RedpointEffect, RPointMask, SPECIALWINDOW } from "../../Common/Define";
import { JXColor } from "../../Common/JXColor";
import { L } from "../../Common/Language";
import { VIEW_ID } from "../../Common/UI";
import UICreate from "../../Common/UICreate";
import { Res } from "../../Common/UIResources";
import { JXLocales } from "../../Common/Zh";
import RJXItem from "../../Data/RunTime/RunRaw/RJXItem";
import GameMgr from "../../Logic/GameMgr";
import { IHeroSort } from "../../Logic/HeroMgr";
import JXItem from "../Common/JXItem";
import SkillItem from "../Home/SkillItem";
import { JXEHeroBgAniNames } from "../JXBattle/JXULDefine";
import { GCtrl } from './../../../Core/GCtrl';
import { CMsg } from './../../Common/Define';
import HeroChange from "./HeroChange";

const { ccclass, property, menu, executeInEditMode } = cc._decorator;
@ccclass @menu('View/Hero/DetailsCtrl')

export default class DetailsCtrl extends GViewBase {
    @property({ type: sp.Skeleton, tooltip: "英雄品质光芒" }) sk_trait: sp.Skeleton = null;
    @property({ type: sp.Skeleton, tooltip: "英雄升级" }) sk_sengji: sp.Skeleton = null;
    @property({ type: cc.Node, tooltip: "英雄技能" }) skill: cc.Node = null;
    @property({ type: cc.Label, tooltip: "英雄职业" }) heroGroup: cc.Label = null;
    @property({ type: cc.Label, tooltip: "英雄名字" }) heroName: cc.Label = null;
    @property({ type: cc.Node, tooltip: "英雄星级图示" }) heroStar: cc.Node = null;
    @property({ type: cc.Node, tooltip: "英雄战力" }) heroBatter: cc.Node = null;
    @property({ type: cc.Node, tooltip: "英雄等级" }) heroLvLab: cc.Node = null;
    @property({ type: cc.ProgressBar, tooltip: "英雄等级进度条" }) heroLvVal: cc.ProgressBar = null;
    @property({ type: cc.Node, tooltip: "英雄星级数值" }) heroStarLab: cc.Node = null;
    @property({ type: cc.Sprite, tooltip: "英雄等级升级与突破" }) heroLvBtn: cc.Sprite = null;
    @property({ type: cc.Label, tooltip: "英雄经验值" }) expNum: cc.Label = null;
    @property({ type: cc.Label, tooltip: "英雄升级金币数量" }) lvCoinNum: cc.Label = null;
    @property({ type: cc.Node, tooltip: "英雄升级金币按钮" }) lvCoinNode: cc.Node = null;
    @property({ type: cc.Label, tooltip: "星级升级碎片数" }) starNum: cc.Label = null;
    @property({ type: cc.ProgressBar, tooltip: "英雄星级进度条" }) heroStarVal: cc.ProgressBar = null;
    @property({ type: cc.Node, tooltip: "展示属性框" }) attribute: cc.Node = null;
    @property({ type: cc.Node, tooltip: "攻击范围框" }) range: cc.Node = null;
    @property({ type: cc.Label, tooltip: "战力" }) powal: cc.Label = null;
    @property({ type: cc.ScrollView, tooltip: "装备视图" }) equipScrollView: cc.ScrollView = null;
    @property({ type: cc.Node, tooltip: "属性视图" }) attributeView: cc.Node = null;
    @property({ type: cc.Node, tooltip: "可视区域" }) view: cc.Node = null;
    @property({ type: cc.Node, tooltip: "装备存放节点" }) content: cc.Node = null;
    @property({ type: cc.Node, tooltip: "装备图标穿戴渲染节点左边" }) equipmentL: cc.Node = null;
    @property({ type: cc.Node, tooltip: "装备回收图标" }) delEquip: cc.Node = null;
    @property({ type: HeroChange, tooltip: "英雄人物" }) HeroChange: HeroChange = null;
    @property({ type: cc.Node, tooltip: "升级" }) lvUpBtn: cc.Node = null;
    @property({ type: cc.Node, tooltip: "升星" }) addStarBtn: cc.Node = null;
    @property({ type: cc.Sprite, tooltip: "英雄战力涨跌幅箭头" }) arrowLv: cc.Sprite = null;
    @property({ type: cc.Node }) equipToggle: cc.Node = null;
    /**英雄热数据 */
    private _IHeroData: IHeroData = null;
    /**英雄静态数据 */
    private _SHeroData: SHeroDataRaw = null;
    /**是否突破 */
    private _Breach: boolean = false;
    /**下一个等级数据 */
    private _nextData: SLvDataRaw = null;
    /**当前等级数据 */
    private _curData: SLvDataRaw = null;
    /**装备视图 */
    private _listView: GListView = null;
    /**装备部位数组 */
    private equipArr: Array<cc.Node> = [];
    /**装备品质名称 */
    private _carName = [];
    /**升级金币数量 */
    private _qhItem: JXItem = null;
    /**战力 */
    private _zhangLi: number = 0;
    /**首次进入界面 */
    onGLoad() {
        GCtrl.ES.on(CMsg.client.hero.onHeroAddStar, this, this.onHeroAddStar.bind(this), PRIORITY_VIEW);
        GCtrl.ES.on(CMsg.client.hero.onHeroLvUp, this, this.onHeroLvUp.bind(this), PRIORITY_VIEW);
        GCtrl.ES.on(CMsg.client.equip.onEquipPutOn, this, this.onEquipPutOn.bind(this), PRIORITY_VIEW);
        GCtrl.ES.on(CMsg.client.equip.onEquipPutOff, this, this.onEquipPutOff.bind(this), PRIORITY_VIEW);
        GCtrl.ES.on(CMsg.client.equip.ondelEquip, this, this.ondelEquip.bind(this), PRIORITY_VIEW);
        GCtrl.ES.on(CMsg.client.hero.onHeroBreach, this, this.onHeroBreach.bind(this), PRIORITY_VIEW);
        GCtrl.ES.on(CMsg.client.bag.onBagItemChange, this, this.onBagItemChange.bind(this), PRIORITY_VIEW);
        for (let i = 0; i < this.equipmentL.children.length; i++) {
            this.equipArr.push(this.equipmentL.children[i]);
        }
        this.initCarName();
    }

    protected onBagItemChange() {
        this.heroLvLab.getComponent(cc.Label).string = this._IHeroData.lv + '';
        this.heroStarLab.getComponent(cc.Label).string = this._IHeroData.star + '';
        this.initStarVal();
        this.initHeroLv();
    }
    /**跳转加持 */
    protected bless() {
        // console.log('跳转加持界面');
        let level = GameMgr.lUserData.level;
        let aidOpen = GameMgr.systemConfig.value(JXDef.SYS_CONFIG_KEY.aidOpen);
        if (level >= aidOpen) {
            // GameMgr.sdkMgr.umaSetPoint(JXDef.umaPoint.bless, { msg: this._SHeroData.name + "进入加持界面" });
            GameMgr.jumpToMgr.jumpGoTo(VIEW_ID.blessCtrl, this._IHeroData, this._SHeroData);
        } else {
            let str = "通过第" + aidOpen + "关开启合成强化界面";
            GameMgr.uiMgr.showToast(str);
        }
    }

    protected setRedPoint() {
        if (this._IHeroData) {
            let isLvUp = GameMgr.heroMgr.checkHeroCanGrow(this._IHeroData.tableId, false);
            let isTuPo = GameMgr.heroMgr.checkHeroCanGrow(this._IHeroData.tableId, true);
            let isAddStart = GameMgr.heroMgr.checkHeroCanAddStar(this._IHeroData.tableId)
            let isBaset = GameMgr.heroMgr.checkHeorBastEquip(this._IHeroData);
            GameMgr.redMgr.setRPointView(this.lvUpBtn, this.lvUpBtn, (isLvUp || isTuPo), RedpointEffect.REDPOINT);
            GameMgr.redMgr.setRPointView(this.equipToggle, this.equipToggle, isBaset, RedpointEffect.REDPOINT);
            GameMgr.redMgr.setRPointView(this.addStarBtn, this.addStarBtn, isAddStart, RedpointEffect.REDPOINT);
        }
    }

    /**初始化 */
    protected init() {
        this.heroLvLab.getComponent(cc.Label).string = this._IHeroData.lv + '';
        this.heroStarLab.getComponent(cc.Label).string = this._IHeroData.star + '';
        this.initStarVal();
        this.initHeroLv();
        this.initEmbattle();
        this.initEquipFrame();
        this.showAttribute();
        this.initSkill();
        this.initTrait();
        this.setRedPoint();
        // GameMgr.sdkMgr.umaSetPoint(JXDef.umaPoint.FeatureCtrl, { msg: L(JXLocales.tower.heroTrait, this._IHeroData.trait) })//L(JXLocales.tower.heroTrait, this._IHeroData.trait)
        let herotarit = GameMgr.lUserData.herotarit(this._IHeroData.trait);
        GameMgr.sdkMgr.umaSetPoint(JXDef.umaPoint.detailsCtrl, { msg: this._SHeroData.name + JXLocales.tower.heroTrait + herotarit })
        GameMgr.sdkMgr.umaSetPoint(JXDef.umaPoint.detailsCtrl, { msg: this._SHeroData.name + L(JXLocales.tower.heroStar, this._IHeroData.star) })
    }

    protected helpBtn() {
        let cost = [SPECIALWINDOW.HELP, this._IHeroData.tableId, 1];
        GameMgr.jumpToMgr.jumpGoTo(VIEW_ID.currencyFrame, cost, 1);
    }

    /**英雄品质光芒 */
    protected initTrait() {
        switch (this._IHeroData.trait) {
            case HERO_TRAIT.WHITE:
                {
                    this.sk_trait.setAnimation(0, JXEHeroBgAniNames.white, true)
                    break;
                }
            case HERO_TRAIT.GREEN:
                {
                    this.sk_trait.setAnimation(0, JXEHeroBgAniNames.green, true)
                    break;
                }
            case HERO_TRAIT.BLUE:
                {
                    this.sk_trait.setAnimation(0, JXEHeroBgAniNames.blue, true)
                    break;
                }
            case HERO_TRAIT.PURPLE:
                {
                    this.sk_trait.setAnimation(0, JXEHeroBgAniNames.purple, true)
                    break;
                }
            case HERO_TRAIT.YELLOW:
                {
                    this.sk_trait.setAnimation(0, JXEHeroBgAniNames.yellow, true)
                    break;
                }
            case HERO_TRAIT.RED:
                {
                    this.sk_trait.setAnimation(0, JXEHeroBgAniNames.red, true)
                    break;
                }

            default:
                break;
        }

    }

    /**穿戴装备 */
    protected onEquipPutOn(_, param: GParam) {
        let info = param.get<EquipPutInfo>();
        this._IHeroData = GameMgr.rHeroData.getHero(info.heroId);
        AudioMgr.Ins().playEffect(Res.audio.wear);
        this.initEmbattle();
        this.initHeroLv();
        this.initEquipFrame();
        this.showAttribute();
        this.setRedPoint();
        GameMgr.redMgr.sendValueSettingMsg(RPointMask.RPM_Have_Base, false);
    }

    /**回收装备 */
    protected ondelEquip() {
        this.initEmbattle();
        this.setRedPoint();
        this.initEquipFrame();
        GameMgr.redMgr.sendValueSettingMsg(RPointMask.RPM_Have_Base, false);
    }

    /**英雄升级突破 */
    protected onHeroBreach(data, Idata: number) {
        this._IHeroData = GameMgr.rHeroData.getHero(Idata);
        this.initHeroLv();
        this.showAttribute();
        this.initSkill(Idata);
        this.initTrait();
        this.setRedPoint();
        this.initEquipFrame();
        GameMgr.redMgr.sendValueSettingMsg(RPointMask.RPM_Hero_Tupo, false)
    }

    /**英雄升级 */
    protected onHeroLvUp(data, Idata: number) {
        this._IHeroData = GameMgr.rHeroData.getHero(Idata);
        this.sk_sengji.setAnimation(0, JXEHeroBgAniNames.shengji, false)
        this.initHeroLv();
        this.showAttribute();
        this.initSkill(Idata);
        this.initTrait();
        this.setRedPoint();
        this.initEquipFrame();
        GameMgr.redMgr.sendValueSettingMsg(RPointMask.RPM_Hero_LvUp, false)
    }

    /**卸下穿戴装备 */
    protected onEquipPutOff(_, param: GParam) {
        let info = param.get<EquipPutInfo>();
        // console.log("卸下穿戴装备", info);
        this.equipArr[info.site].destroyAllChildren();
        this._IHeroData = GameMgr.rHeroData.getHero(info.heroId);
        // console.log("装备初始化装备视图", this._IHeroData);
        this.initEmbattle();
        this.initHeroLv();
        this.initEquipFrame();
        this.showAttribute();
        this.setRedPoint();
        GameMgr.redMgr.sendValueSettingMsg(RPointMask.RPM_Have_Base, false);
    }

    /**点击装备按钮 */
    protected equipClick() {
        this.equipScrollView.node.active = true;
        this.attributeView.active = false;
    }

    /**点击属性按钮 */
    protected attributeClick() {
        this.equipScrollView.node.active = false;
        this.attributeView.active = true;
    }

    /**英雄升星 */
    protected onHeroAddStar(data, Idata: number) {
        // console.log('英雄升星');
        this._IHeroData = GameMgr.rHeroData.getHero(Idata);
        this.initStarVal();
        this.showAttribute();
        this.initTrait();
        this.initHeroLv();
        this.setRedPoint();
        this.initEquipFrame();
        this.sk_sengji.setAnimation(0, JXEHeroBgAniNames.shengji, false);
        // GameMgr.sdkMgr.umaSetPoint(JXDef.umaPoint.heroCtrl, { msg: this._SHeroData.name + "进行升星" });
        GameMgr.redMgr.sendValueSettingMsg(RPointMask.RPM_Hero_AddStar, false)
    }



    /**初次进入界面 */
    onGStart(Idata: IHeroData, Sdata: SHeroDataRaw) {
        this._IHeroData = Idata;
        let HeroZhangLi: HeroZhangLi = {
            heroId: this._IHeroData.tableId
        }
        GCtrl.ES.emit(CMsg.client.hero.onGetHeroZhangLi, new GParam(HeroZhangLi));
        this._SHeroData = Sdata;
        this.heroGroup.string = JXLocales.heroGroup["group" + this._SHeroData.type];
        this.heroName.string = this._SHeroData.name;
        this.initRange();
        this.initHeroSpine();
        this.init();
        this.equipClick();

    }

    /**初始化View */
    protected initEmbattle() {
        // console.log("初始化View");
        if (!this._listView) {
            this.assetImpl.prefab(Res.prefab.item.jxItem, (prefab: cc.Prefab) => {
                this._listView = new GListView({
                    scrollview: this.equipScrollView,
                    mask: this.view,
                    content: this.content,
                    itemTpl: cc.instantiate(prefab),
                    itemSetter: this.onItemSetter.bind(this),
                    column: 6,
                    row: 3,
                    gapY: 20,
                    gapX: 20,
                    padingY: 0,
                    padingX: 10,
                    isCbClass: true,
                    isWidget: false,
                });
                this.dealWithData()
            })
        } else {
            this.dealWithData()
        }
    }

    /**初始每个装备框 */
    public onItemSetter(item: JXItem, data: string, index: number) {
        if (data) {
            let equipData = GameMgr.RBagData.getEquipDataById(data);
            let value = equipData.itemData;
            let equip = value;
            let jumpEquip: jumpEquip = {
                insId: equipData.insId,
                bool: item.equipUse,
                site: 0
            }
            let isRed = GameMgr.heroMgr.checkEquipIsBast(this._IHeroData.equips[value.raw.seat], equipData.insId, this._IHeroData.lv);
            GameMgr.redMgr.setRPointView(item.node, item.node, isRed, RedpointEffect.REDPOINT);
            item.eqlv1.node.active = false;
            item.setView(equip, ITEM_DETAIL_FLAG.TOUCH | ITEM_DETAIL_FLAG.ICON_SCALE, () => {
                GameMgr.jumpToMgr.jumpGoTo(VIEW_ID.EquipDetailsCtrl, equipData, jumpEquip, this._IHeroData);
            }, equipData.insId);
            item.setTouch(this._IHeroData, this.equipArr, this.delEquip);
        } else {
            // cc.warn('');
            let equip = new RJXItem([0, 0, 0]);
            item.eqlv1.node.active = false;
            GameMgr.redMgr.setRPointView(item.node, item.node, false, RedpointEffect.REDPOINT);
            item.setView(equip, ITEM_DETAIL_FLAG.NULLICON);
        }

    }

    /**处理数据 */
    protected dealWithData() {
        let curMax = 18;
        let data = GameMgr.RBagData.getHeroEquip(this._IHeroData.tableId);
        let equip = data.equip;
        let book = data.book;
        equip = this.isWear(equip);

        book = GameMgr.RBagData.getAllBook();
        book = this.isWear(book);

        curMax -= equip.length;
        curMax -= book.length;
        if (curMax < 0) {
            curMax = 0;
        }
        let blank = new Array(curMax);
        let equipSorts = [IHeroSort.sortEquipZhanli];
        let equipSort = (a: string, b: string) => {
            let equipDataA = GameMgr.RBagData.getEquipDataById(a);
            let equipDataB = GameMgr.RBagData.getEquipDataById(b);
            return IHeroSort.sortsEquire(equipSorts, equipDataA, equipDataB);
        }
        equip.sort(equipSort);
        let arr = [...equip, ...book, ...blank];
        this._listView.setData(arr);
    }

    /**筛选是否穿戴过 */
    protected isWear(arr: string[]): string[] {
        let boolEquip = false;//是否穿戴该装备
        let brush = [];//刷新数组
        // console.log('处理数据', arr);
        arr.forEach((value, index) => {
            boolEquip = false;//未穿戴该装备
            this._IHeroData.equips.forEach((equips) => {
                if (boolEquip) {
                    return;
                }
                if (value == equips) {
                    brush.push(value);//存入需要刷新的数组
                    boolEquip = true;//已穿戴改装备
                }
            })
            //处理背包里已穿戴的装备 返回需要渲染的装备
            if (index == arr.length - 1) {
                let length = arr.length;
                for (let i = 0; i < length; i++) {
                    for (let j = 0; j < brush.length; j++) {
                        if (brush[j] == arr[i]) {
                            arr.splice(i, 1);
                        }
                    }
                }
                // console.log('处理数据1', arr);
            }
        })
        return arr
    }

    /**判断兵书是否被其它英雄穿戴过 */
    protected isWearBookHero() {

    }


    /**初始技能图标渲染 */
    protected initSkill(id?: number) {
        this.assetImpl.prefab(Res.prefab.item.skillItem, (prefab: cc.Prefab) => {
            //英雄持有技能
            this.skill.destroyAllChildren();
            let heroSkill = GameMgr.skillData.getHeroSkillData(this._IHeroData.tableId);
            let heroUseSkill = GameMgr.skillData.getHeroUseSkill(this._IHeroData.tableId, this._IHeroData.lv);

            let skill = this._IHeroData.skillIds;


            if (id) {
                heroUseSkill.forEach((v, index) => {
                    if (v != skill[index]) {
                        // console.log("英雄解锁新技能");
                        let data = GameMgr.skillData.getRaw<SSkillDataRaw>(v);
                        GameMgr.jumpToMgr.jumpGoTo(VIEW_ID.skillPage, data, 1);
                    }
                })
            }

            let HeroSetSkill: HeroSetSkill = {
                heroId: this._IHeroData.tableId,
                skill: heroUseSkill
            }

            GCtrl.ES.emit(CMsg.client.hero.onSetSkill, new GParam(HeroSetSkill))
            heroSkill.forEach((v: SSkillDataRaw, index) => {
                let bool = false;
                let node = cc.instantiate(prefab);
                let comp = node.getComponent(SkillItem);
                node.parent = this.skill;
                if (heroUseSkill[index]) {
                    bool = true;
                }
                comp.setView(v, bool);
            })
        })
    }

    /**初始英雄人物 */
    protected initHeroSpine() {
        this.HeroChange.init(this._IHeroData);
    }

    /**初始化6个装备框展示装备图 */
    protected initEquipFrame() {
        let equips = this._IHeroData.equips;
        this.assetImpl.prefab(Res.prefab.item.jxItem, (prefab: cc.Prefab) => {
            equips.forEach((value, index) => {
                this.equipArr[index].destroyAllChildren();
                if (value == '-1' || !value) {
                    var img = new cc.Node("New Sprite");
                    var sprite = img.addComponent(cc.Sprite);
                    img.parent = this.equipArr[index];
                    if (index <= 2) {
                        this.assetImpl.spriteAtlasFrame(sprite, Res.texture.views.heroDetail, 'img' + index);
                    } else {
                        this.assetImpl.spriteAtlasFrame(sprite, Res.texture.views.heroDetail, 'book');
                    }
                    this.assetImpl.spriteAtlasFrame(this.equipArr[index].getComponent(cc.Sprite), Res.texture.views.heroDetail, 'equipIcon');
                    return;
                }
                let comp = this.assetImpl.addGChild<JXItem>(prefab);
                if (value) {
                    let equipData = GameMgr.RBagData.getEquipDataById(value);
                    if (equipData) {
                        let equipValue = equipData.itemData;
                        comp.equipUse = true;
                        comp.node.parent = this.equipArr[index];
                        this.assetImpl.spriteAtlasFrame(this.equipArr[index].getComponent(cc.Sprite), Res.texture.views.common, "equip_" + equipData.quality)
                        comp.node.setPosition(0, 0);
                        let jumpEquip: jumpEquip = {
                            insId: equipData.insId,
                            bool: comp.equipUse,
                            site: index,
                        }
                        comp.initOffEvent();
                        comp.setView(equipValue, ITEM_DETAIL_FLAG.NO_BG_SHOWSLV, () => {
                            GameMgr.jumpToMgr.jumpGoTo(VIEW_ID.EquipDetailsCtrl, equipData, jumpEquip, this._IHeroData);
                        }, equipData.insId);
                    }
                }
            })
        })
    }

    /**初始化卡牌品质名称 */
    protected initCarName() {
        let white = GameMgr.systemConfig.value(JXDef.SYS_CONFIG_KEY.white);
        this._carName.push(white);
        let green = GameMgr.systemConfig.value(JXDef.SYS_CONFIG_KEY.green);
        this._carName.push(green);
        let Blue = GameMgr.systemConfig.value(JXDef.SYS_CONFIG_KEY.Blue);
        this._carName.push(Blue);
        let purple = GameMgr.systemConfig.value(JXDef.SYS_CONFIG_KEY.purple);
        this._carName.push(purple);
        let orange = GameMgr.systemConfig.value(JXDef.SYS_CONFIG_KEY.orange);
        this._carName.push(orange);
        let red = GameMgr.systemConfig.value(JXDef.SYS_CONFIG_KEY.red);
        this._carName.push(red);
        // console.log('展示属性', GameMgr.systemConfig.value(JXDef.SYS_CONFIG_KEY.white));
        // console.log('this._carName', this._carName);
    }

    /**初始星星进度条 以及星星栏*/
    protected initStarVal() {
        let star = this._IHeroData.star;
        if (star >= this._SHeroData.star.length * 5) {
            this.addStarBtn.children[0].children[0].getComponent(cc.Label).string = '满级';
            this.addStarBtn.getComponent(cc.Button).interactable = false;
        }
        let starObj = GameMgr.heroMgr.getChipNeedByStar(star);
        let bagStar = GameMgr.RBagData.getMegreItems(this._IHeroData.tableId, ITEM_TYPE.PROP).num;//已有星数级
        let count = this._SHeroData.star[starObj.lv];//下一个星位升级数量
        let val = bagStar / count;
        this.starNum.string = bagStar + '/' + count;
        if (val >= 1) {
            this.setLoadProgress(1, this.heroStarVal);
        } else if (val <= 0) {
            this.setLoadProgress(0, this.heroStarVal);
        } else {
            this.setLoadProgress(val, this.heroStarVal);
        }
        //设置星星显隐
        for (let i = 0; i < this.heroStar.children.length; i++) {
            if (i > starObj.count - 1) {
                this.heroStar.children[i].active = false;
            } else {
                this.heroStar.children[i].color = cc.Color.WHITE;
                this.heroStar.children[i].active = true;
                this.assetImpl.spriteAtlasFrame(this.heroStar.children[i].getComponent(cc.Sprite), Res.texture.views.icon, 'icon_star' + (starObj.lv + 1));
            }
        }
        this.heroStarLab.getComponent(cc.Label).string = this._IHeroData.star + '';
    }



    /**初始英雄等级 */
    protected initHeroLv() {
        this.heroLvLab.getComponent(cc.Label).string = this._IHeroData.lv + '';
        var heroLv = this._IHeroData.lv;
        var heroExp = this._IHeroData.exp;
        var maxLv = GameMgr.lvData.getMaxlv();
        var img = null;
        //当前等级数据
        this._curData = GameMgr.lvData.getRaw<SLvDataRaw>(heroLv);
        //是否满级
        if (heroLv >= maxLv.lv) {
            //下一个等级数据
            this._nextData = GameMgr.lvData.getRaw<SLvDataRaw>(heroLv);
            //缺个已满级效果
        } else {
            //下一个等级数据
            this._nextData = GameMgr.lvData.getRaw<SLvDataRaw>(heroLv + 1);
            //false 为升级  true为突破
            this._Breach = this._nextData.quality != this._curData.quality && heroExp >= this._nextData.exp ? true : false;
            // img = this._Breach ? "aa" : "coinBtn";
            img = this._Breach ? "icon_201" : "icon_101";
        }
        //经验值
        this.expNum.string = heroExp + '/' + this._nextData.exp;
        //处理图片
        this.assetImpl.spriteAtlasFrame(this.heroLvBtn, Res.texture.views.icon, img);
        //设置经验进度条
        let val = heroExp / this._nextData.exp;
        // console.log("val", val, heroExp, this._nextData.exp);
        if (val >= 1) {
            this.setLoadProgress(1, this.heroLvVal);
        } else if (val <= 0) {
            this.setLoadProgress(0, this.heroLvVal);
        } else {
            this.setLoadProgress(val, this.heroLvVal);
        }
        var num = null;
        this.heroLvLab.getComponent(cc.Label).string = this._curData.showLv + '';
        if (this._Breach) {
            num = 1;
        } else {
            num = GameMgr.lvData.getRaw<SLvDataRaw>(Number(heroLv + 1)).gold;
        }

        // this.lvCoinNum.string = num + '';

        this.assetImpl.prefab(Res.prefab.item.jxItem, (prefab: cc.Prefab) => {
            if (!this._qhItem) {
                let comp = this.assetImpl.addGChild<JXItem>(prefab);
                comp.node.parent = this.lvCoinNode;
                comp.node.setPosition(5, 0);
                this._qhItem = comp;
            }
            let btn = null;
            if (this._Breach) {
                let pill = GameMgr.itemData.getRaw<SItemDataRaw>(Number(200 + this._nextData.quality));
                let coin = new RJXItem([pill.id, ITEM_TYPE.PROP, 1])
                btn = coin;
            } else {
                btn = new RJXItem([CURRENCY.GOLD, 3, Math.floor(num)]);
            }

            this._qhItem.setView(btn, ITEM_DETAIL_FLAG.MATERIAL_STYLE_LINE | ITEM_DETAIL_FLAG.MATERIAL_NO_HAVE | ITEM_DETAIL_FLAG.NOT_TOUCH | ITEM_DETAIL_FLAG.LVFONTCHANGE)
        })

    }

    /**升级英雄经验 */
    protected upgradeLv() {
        var maxLv = GameMgr.lvData.getMaxlv();
        var heroLv = this._IHeroData.lv;
        if (heroLv >= maxLv.lv) {
            return;
        }
        //是否可以突破
        if (this._Breach) {
            let pill = GameMgr.itemData.getRaw<SItemDataRaw>(Number(200 + this._nextData.quality));
            let coin = new RJXItem([pill.id, ITEM_TYPE.PROP, 1])
            let result = GameMgr.itemMgr.testCost(coin, 1, true)
            //是否有对应卡级突破丹
            if (result.enough) {
                this._Breach = false;
                this.attribute.destroyAllChildren();
                AudioMgr.Ins().playEffect(Res.audio.tupo);
                GCtrl.ES.emit(CMsg.client.hero.onHeroLvUp, this._IHeroData.tableId);
                GCtrl.ES.emit(CMsg.client.hero.onHeroBreach, this._IHeroData.tableId);
                GCtrl.ES.emit(CMsg.client.bag.onBagItemChange, [[pill.id, ITEM_TYPE.PROP, -1]]);
                // GameMgr.sdkMgr.umaSetPoint(JXDef.umaPoint.heroCtrl, { msg: this._SHeroData.name + "进行突破" })

                this.sk_sengji.setAnimation(0, JXEHeroBgAniNames.shengji, false)
            } else {
                GameMgr.uiMgr.showToast(result.tip)
            }
        } else {
            //达到等级需求经验值升级
            if (this._IHeroData.exp >= this._nextData.exp) {
                let num = GameMgr.lvData.getRaw<SLvDataRaw>(Number(heroLv + 1)).gold;
                let coin = new RJXItem([CURRENCY.GOLD, ITEM_TYPE.CURRENCY, num])
                let result = GameMgr.itemMgr.testCost(coin, 1, true);
                if (result.enough) {
                    GCtrl.ES.emit(CMsg.client.bag.onBagItemChange, [[CURRENCY.GOLD, ITEM_TYPE.CURRENCY, -num]])
                    this.attribute.destroyAllChildren();
                    AudioMgr.Ins().playEffect(Res.audio.lvUp);
                    // GameMgr.sdkMgr.umaSetPoint(JXDef.umaPoint.heroCtrl, { msg: this._SHeroData.name + "进行升级" })
                    GCtrl.ES.emit(CMsg.client.hero.onHeroLvUp, this._IHeroData.tableId);
                    this.sk_sengji.setAnimation(0, JXEHeroBgAniNames.shengji, false)
                } else {
                    GameMgr.uiMgr.showToast(result.tip)
                }
            } else {
                GameMgr.uiMgr.showToast(JXLocales.tip.lvExp);
            }
        }
    }

    /**升级星星 */
    protected upgradeStar() {
        let star = this._IHeroData.star;
        //满星级
        if (star >= this._SHeroData.star.length * 5) {
            return;
        }
        let starObj = GameMgr.heroMgr.getChipNeedByStar(star);
        // let bagStar = GameMgr.RBagData.getMegreItems(this._IHeroData.tableId, ITEM_TYPE.PROP).type;
        let count = this._SHeroData.star[starObj.lv];
        let prop = new RJXItem([this._SHeroData.id, ITEM_TYPE.PROP, count])
        let result = GameMgr.itemMgr.testCost(prop, 1, true);
        if (result.enough) {
            //升级星级
            //扣除碎片
            GCtrl.ES.emit(CMsg.client.bag.onBagItemChange, [[this._IHeroData.tableId, ITEM_TYPE.PROP, -count]])
            //更新设置英雄热数据
            GCtrl.ES.emit(CMsg.client.hero.onHeroAddStar, this._IHeroData.tableId);
        } else {
            GameMgr.uiMgr.showToast(result.tip);
        }
        // if (bagStar >= count) {
        //     //升级星级
        //     this._IHeroData.star += 1;
        //     //扣除碎片
        //     GCtrl.ES.emit(CMsg.client.bag.onBagItemChange, [[this._IHeroData.tableId, ITEM_TYPE.PROP, -count]])
        //     //更新设置英雄热数据
        //     GCtrl.ES.emit(CMsg.client.hero.onHeroAddStar, this._IHeroData.tableId);
        // }
    }

    /**设置进度条 英雄等级 英雄星级 */
    protected setLoadProgress(val: number, progressBar: cc.ProgressBar) {
        if (!progressBar) return;
        progressBar.progress = Math.min(val, 1);
    }

    /**展示属性 */
    protected showAttribute() {
        this.attribute.destroyAllChildren();


        this.assetImpl.font(Res.font.fzcy, (font) => {
            //英雄品质
            let pinzhi = JXLocales.propts["info" + 1000];
            let lab = UICreate.label(pinzhi);
            lab.fontSize = 22;
            lab.lineHeight = 25;
            lab.node.color = JXColor.C000000;
            // lab.addComponent(cc.LabelOutline);
            // let labLine = lab.getComponent(cc.LabelOutline);
            // labLine.color = JXColor.C000000;
            // labLine.width = 1;
            lab.font = font;
            lab.spacingX = 3;

            let lvData: SLvDataRaw = GameMgr.lvData.getIdByInfo(this._IHeroData.lv);
            let pinzhiNum = UICreate.label(this._carName[this._curData.quality - 1] + lvData.showLv + '级');
            pinzhiNum.fontSize = 30;
            pinzhiNum.lineHeight = 30;
            pinzhiNum.enableItalic = true;
            pinzhiNum.node.color = JXColor.Cffffff;
            pinzhiNum.addComponent(cc.LabelOutline);
            let pinzhiNumLab = pinzhiNum.getComponent(cc.LabelOutline);
            pinzhiNumLab.color = cc.color(87, 0, 255, 255);
            pinzhiNumLab.width = 2;
            pinzhiNum.node.anchorX = 0;
            pinzhiNum.spacingX = 3;
            pinzhiNum.cacheMode = cc.Label.CacheMode.NONE;
            //品质数字
            this.assetImpl.font(Res.font.ysbth, (font1) => {
                pinzhiNum.font = font1;
            })
            var pinzhiNode = new cc.Node();
            pinzhiNode.addComponent(cc.Layout);
            let pinzhiNodeLayout = pinzhiNode.getComponent(cc.Layout);
            pinzhiNodeLayout.type = cc.Layout.Type.HORIZONTAL;
            pinzhiNodeLayout.spacingX = -2;
            pinzhiNodeLayout.resizeMode = cc.Layout.ResizeMode.CONTAINER;
            pinzhiNode.anchorX = 0;
            pinzhiNode.addChild(lab.node);
            pinzhiNode.addChild(pinzhiNum.node);
            this.attribute.addChild(pinzhiNode);

            //英雄耗粮
            let grainNum = UICreate.label(this._SHeroData.food + '');
            grainNum.fontSize = 22;
            grainNum.lineHeight = 25;
            grainNum.node.color = cc.color(255, 245, 83, 255);
            grainNum.addComponent(cc.LabelOutline);
            let grainNumLine = grainNum.getComponent(cc.LabelOutline);
            grainNumLine.color = JXColor.C000000;
            grainNumLine.width = 2;
            grainNum.node.anchorX = 0;
            grainNum.spacingX = 3;
            this.assetImpl.font(Res.font.ysbth, (font2) => {
                grainNum.font = font2;
            })


            let grain = JXLocales.propts["info" + 1001];
            let grainLab = UICreate.label(grain);
            grainLab.fontSize = 22;
            grainLab.lineHeight = 25;
            grainLab.spacingX = 3;
            grainLab.node.color = JXColor.C000000;
            // grainLab.addComponent(cc.LabelOutline);
            // let grainLabLine = grainLab.getComponent(cc.LabelOutline);
            // grainLabLine.color = JXColor.C000000;
            // grainLabLine.width = 2;
            grainLab.font = font;

            var labs = new cc.Node();
            labs.addComponent(cc.Layout);
            let layout = labs.getComponent(cc.Layout);
            layout.type = cc.Layout.Type.HORIZONTAL;
            layout.resizeMode = cc.Layout.ResizeMode.CONTAINER;
            layout.spacingX = 3;
            labs.addChild(grainLab.node);
            labs.addChild(grainNum.node);
            labs.anchorX = 0;
            this.attribute.addChild(labs);

            //英雄属性
            this._IHeroData.propts.forEach((value, index) => {
                if (value && index < 6) {
                    let numStr = value < 1 ? ((value * 100).toFixed(2) + "%") : value.toString();
                    if (index > 2) {
                        numStr = ((value * 100).toFixed(2) + "%");
                    }
                    // let numStr = ((value * 100).toFixed(2) + "%");
                    let numStrLab = UICreate.label(numStr);
                    numStrLab.fontSize = 22;
                    numStrLab.lineHeight = 25;
                    this.assetImpl.font(Res.font.ysbth, (font2) => {
                        numStrLab.font = font2;
                    })
                    numStrLab.node.color = cc.color(109, 255, 246, 255);
                    numStrLab.spacingX = 2;
                    numStrLab.addComponent(cc.LabelOutline);
                    let numStrLabLine = numStrLab.getComponent(cc.LabelOutline);
                    numStrLabLine.color = JXColor.C000000;
                    numStrLabLine.width = 2;
                    let str = L(JXLocales.equipPropts["info" + index]);
                    let lab = UICreate.label(str);
                    lab.fontSize = 22;
                    lab.lineHeight = 25;
                    lab.node.color = JXColor.C000000;
                    lab.node.anchorX = 0;
                    lab.spacingX = 3;
                    lab.font = font;
                    var propts = new cc.Node();
                    propts.addComponent(cc.Layout);
                    let proptLayout = propts.getComponent(cc.Layout);
                    proptLayout.type = cc.Layout.Type.HORIZONTAL;
                    proptLayout.resizeMode = cc.Layout.ResizeMode.CONTAINER;
                    proptLayout.spacingX = 3;
                    propts.addChild(lab.node);
                    propts.addChild(numStrLab.node);
                    numStrLab.node.y = -2;
                    propts.anchorX = 0;
                    this.attribute.addChild(propts)
                }
            })
            //英雄战力
            // this.powal.string = '战力：' + LCoin(parseInt(JXMath.getZhanli(this._IHeroData.propts).toString())) + '';

            let COINPAREM: COINPAREM = {
                coin: JXMath.getZhanli(this._IHeroData.propts).toString(),
                add: (JXMath.getZhanli(this._IHeroData.propts) - this._zhangLi).toString(),
            }
            // this.powal.string = '战力：' + parseInt(JXMath.getZhanli(this._IHeroData.propts).toString()) + '';
            this.onAddCoin(COINPAREM);

            let bool: boolean = JXMath.getZhanli(this._IHeroData.propts) - this._zhangLi > 0 ? true : false;
            // console.log('英雄战力', bool);

            if (bool) {

                let anim = this.arrowLv.node.getComponent(cc.Animation);
                this.assetImpl.spriteAtlasFrame(this.arrowLv, Res.texture.views.heroDetail, 'up');
                anim.play('arrow');
                this.scheduleOnce(() => {
                    if (this.arrowLv) {
                        this.arrowLv.spriteFrame = null;
                        anim.stop();
                    }
                }, 1.5)
            } else {
                let anim = this.arrowLv.node.getComponent(cc.Animation);
                anim.play('arrowDown');
                this.assetImpl.spriteAtlasFrame(this.arrowLv, Res.texture.views.heroDetail, 'down');
                this.scheduleOnce(() => {
                    this.arrowLv.spriteFrame = null;
                    anim.stop();
                }, 1.5)
            }
            this._zhangLi = parseInt(JXMath.getZhanli(this._IHeroData.propts).toString());
        })
    }

    /**战力滚动 */
    onAddCoin(param: COINPAREM) {
        // console.log("coin:" + JSON.stringify(param));
        var self = this;
        let constCoin = parseInt(param.coin) - parseInt(param.add);
        var obj = { a: 0 };
        this.powal.string = '战力：' + param.coin;
        cc.tween(obj).to(0.3, { a: 100 }, {
            progress: (start, end, current, ratio) => {
                if (self.node) self.powal.string = constCoin + Math.floor(param.add * ratio);
            }
        }).start();
        // if (param.add > 0) cc.tween(this.nodeIcon).to(0.1, { scale: 1.2 }).to(0.2, { scale: 1 }).start();
    }

    /**初始化英雄攻击范围 */
    protected initRange() {
        this.range.destroyAllChildren();
        let arr = [];
        let arr2 = [];
        let count = -1;
        let raw = this._SHeroData;
        let atkGrids = GameMgr.mapMgr.getAdjacent(raw.scope, new cc.Vec2(3, 3));
        let bool = true;
        for (let j = 0; j < 6; j++) {
            for (let z = 0; z < 7; z++) {
                var spr = UICreate.sprite();
                spr.node.parent = this.range;
                count++;
                atkGrids.forEach((value) => {
                    if (z == value.x && j == value.y) {
                        bool = false;
                        this.rangeImg(RANGE.RANGE3, spr);
                    }
                    if (j == 3 && z == 3) {
                        bool = false;
                        this.rangeImg(RANGE.RANGE2, spr);
                    }
                })

                if (bool) {
                    this.rangeImg(RANGE.RANGE1, spr);
                }
                if (!bool) {
                    bool = true;
                }
            }
        }
        if (this._SHeroData.id == 1006) {
            this.range.scaleY *= -1;
        }
    }

    /**初始化英雄详情页攻击范围图片 */
    protected rangeImg(range: number, sp: cc.Sprite) {
        if (range == RANGE.RANGE1) {
            let atlas = Res.texture.views.heroDetail;
            this.assetImpl.spriteAtlasFrame(sp, atlas, 'AttackBg');
            var spr = UICreate.sprite();
            spr.node.parent = sp.node;
            this.assetImpl.spriteAtlasFrame(spr, atlas, 'AttackBg');
        } else if (range == RANGE.RANGE2) {
            let atlas = Res.texture.views.heroDetail;
            this.assetImpl.spriteAtlasFrame(sp, atlas, 'hero');
            var spr = UICreate.sprite();
            spr.node.parent = sp.node;
            this.assetImpl.spriteAtlasFrame(spr, atlas, 'AttackBg');
        } else if (range == RANGE.RANGE3) {
            let atlas = Res.texture.views.heroDetail;
            this.assetImpl.spriteAtlasFrame(sp, atlas, 'Range');
            var spr = UICreate.sprite();
            spr.node.parent = sp.node;
            this.assetImpl.spriteAtlasFrame(spr, atlas, 'AttackBg');
        }
    }

    /**关闭界面 */
    public onClose() {
        super.onClose();
        GameMgr.jumpToMgr.jumpGoTo(VIEW_ID.heroPage);

        GCtrl.ES.emit(GCtrl.GClientWinOpenEventMsg, VIEW_ID.heroPage);
    }

    public onClickHandler(event:any, str:string){
            if (event.target._name == "detalBtn"){
                GameMgr.jumpToMgr.jumpGoTo(VIEW_ID.comonTipView, ComonTip.shuxing);
            }
            else if (event.target._name == "setingBtn"){
                GameMgr.jumpToMgr.jumpGoTo(VIEW_ID.setting);
            }
            else if (event.target._name == "friendBtn"){
                GameMgr.jumpToMgr.jumpGoTo(VIEW_ID.friendView);
            }
            else if (event.target._name == "emailBtn"){
                GameMgr.jumpToMgr.jumpGoTo(VIEW_ID.emailView);
            }
        }
}   